package account

import (
	"context"
	"encoding/json"
	"fmt"
	"math"
	"reflect"
	"strconv"

	"googee/common/utils"
	"googee/service/account/rpc/account"
	"googee/service/admin/api/internal/svc"
	"googee/service/admin/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AccountListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAccountListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AccountListLogic {
	return &AccountListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AccountListLogic) AccountList(req *types.ListAccountReq) (*types.ListAccountResp, error) {
	//从账户系统获得所有币种的精度
	result, err := l.svcCtx.Account.GetPrecision(l.ctx, &account.Empty{})

	if err != nil {
		logx.Errorf("获得精度失败:%v", result.Precision)
		return nil, err
	}

	all, err := l.svcCtx.AccountModel.FindAllEx(req.Current, req.PageSize)

	if err != nil {
		reqStr, _ := json.Marshal(req)
		logx.Errorf("查询账户列表信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}
	count, _ := l.svcCtx.AccountModel.Count()
	var list []*types.ListAccountData

	utils.MyCopier(&list, all)
	b, err := json.Marshal(list)
	if err == nil {
		logx.Infof("===================> %v", string(b))
	}

	//修正一下数值
	for i := range list {
		v1 := list[i]

		s := reflect.ValueOf(v1).Elem()

		for k1, p1 := range result.Precision {

			{
				k := k1
				x := int(math.Pow10(int(p1)))
				originValue := s.FieldByName(k)

				val, err := strconv.Atoi(originValue.String())

				if err == nil {
					s.FieldByName(k).SetString(fmt.Sprintf("%v", val/x))
				} else {
					s.FieldByName(k).SetString("0")
				}
			}
			{
				k := fmt.Sprintf("%vTrading", k1)
				x := int(math.Pow10(int(p1)))
				originValue := s.FieldByName(k)

				val, err := strconv.Atoi(originValue.String())

				if err == nil {
					s.FieldByName(k).SetString(fmt.Sprintf("%v", val/x))
				} else {
					s.FieldByName(k).SetString("0")
				}
			}
		}
	}

	//获得用户信息
	for _, a := range list {
		u, err := l.svcCtx.UserModel.FindOne(l.ctx, a.Id)
		if err == nil {
			a.Nickname = u.Nickname.String
			a.Name = u.Name.String
		}
	}

	return &types.ListAccountResp{
		Current:  req.Current,
		Data:     list,
		PageSize: req.PageSize,
		Success:  true,
		Total:    count,
		Code:     "000000",
		Message:  "查询账户信息成功",
	}, nil
}
